#include "../include/NetServer.h"
#include <iostream>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

bool NetServer::init()
{
    clientSocket = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(8899);
    serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if(connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) < 0)
    {
        close(clientSocket);
        return false;
    }
    return true;
}

bool NetServer::readBuff()
{
    memset(recvBuff, 0, sizeof(MAXBUFFSIZE));
    if(recv(clientSocket, recvBuff, MAXBUFFSIZE, 0) < 0)
    {
        close(clientSocket);
        return false;
    }
    std:: cout << "read:" << recvBuff << std::endl;
    return true;
}

bool NetServer::writeBuff()
{
    if(send(clientSocket, sendBuff, sizeof(sendBuff), 0) < 0)
    {
        close(clientSocket);
        std::cout << "write fail" << std::endl;
        return false;
    }
    return true;
}

void NetServer::packBuff(const XCY::NetPacket& pack)
{
    memset(sendBuff, 0, sizeof(MAXBUFFSIZE));
    sendBuff[0] = pack.point.x;
    sendBuff[1] = pack.point.y;
    sendBuff[2] = pack.nCurrent_player;
    sendBuff[3] = pack.nRound;
    sendBuff[4] = pack.nWiner;
    sendBuff[5] = pack.nFirstPlayrt;
    writeBuff();
}

void NetServer::parseBuff(XCY::NetPacket& pack)
{
    if(!readBuff())
    {
        std::cout << "read fail" << std::endl;
        return;
    }
    pack.point.x = recvBuff[0];
    pack.point.y = recvBuff[1];
    pack.nCurrent_player = recvBuff[2];
    pack.nRound = recvBuff[3];
    pack.nWiner = recvBuff[4];
    pack.nFirstPlayrt = recvBuff[5];
    std::cout << pack.point.x << "---" << pack.point.y << "----" << pack.nCurrent_player << std::endl;
}

//等待双方玩家就绪
void NetServer::prepareToStart(XCY::PrepareStart &pInfo)
{   
    if(!readBuff())
    {
        std::cout << "read fail" << std::endl;
        return;
    }
    pInfo.point.x = recvBuff[0];
    pInfo.point.y = recvBuff[1];
    pInfo.nIndex = recvBuff[2];
    pInfo.nCurIndex = recvBuff[3];
    std::cout << "pInfo.nIndex:" << pInfo.nIndex << " pInfo.nRount:" << pInfo.nCurIndex << std::endl;
}

int NetServer::getX()
{
    return _x;
}

int NetServer::getY()
{
    return _y;
}